package ludichat.cobbreeding.forge

import ludichat.cobbreeding.Cobbreeding.MOD_ID
import ludichat.cobbreeding.Cobbreeding.init
import ludichat.cobbreeding.CobbreedingClient
import ludichat.cobbreeding.CobbreedingCommands
import net.minecraft.server.packs.PackType
import net.minecraft.network.chat.Component
import net.minecraft.server.packs.PackLocationInfo
import net.minecraft.server.packs.PackResources
import net.minecraft.server.packs.PackSelectionConfig
import net.minecraft.server.packs.PathPackResources
import net.minecraft.server.packs.repository.Pack
import net.minecraft.server.packs.repository.PackSource
import net.neoforged.api.distmarker.Dist
import net.neoforged.fml.ModList
import net.neoforged.fml.common.Mod
import net.neoforged.fml.loading.FMLEnvironment
import net.neoforged.neoforge.common.NeoForge
import net.neoforged.neoforge.event.AddPackFindersEvent
import net.neoforged.neoforge.event.RegisterCommandsEvent
import thedarkcolour.kotlinforforge.neoforge.forge.MOD_BUS
import java.util.Optional

@Mod(MOD_ID)
object Cobbreeding {
    init {
        init()

        if (FMLEnvironment.dist == Dist.CLIENT) {
            CobbreedingClient.init()
        }

        with(MOD_BUS)
        {
            addListener(this@Cobbreeding::onAddPackFindersEvent)
            addListener(CobbreedingNeoforgeNetworkManager::registerMessages)
        }
        with(NeoForge.EVENT_BUS)
        {
            addListener(this@Cobbreeding::registerCommands)
        }
    }

    fun onAddPackFindersEvent(event: AddPackFindersEvent) {
        if (event.packType != PackType.CLIENT_RESOURCES) {
            return
        }

        val modFile = ModList.get().getModFileById(MOD_ID).file
        val path = modFile.findResource("pasturefix")

//        val factory = ResourcePackProfile.PackFactory { name -> PathPackResources(name, true, path) }
        // TODO: watch what Cobblemon does if doesn't work
        val factory = object: Pack.ResourcesSupplier {
            override fun openPrimary(info: PackLocationInfo): PackResources {
                return PathPackResources(info, path)
            }

            override fun openFull(info: PackLocationInfo, meta: Pack.Metadata): PackResources {
                return PathPackResources(info, path)
            }
        }

        val profile = Pack.readMetaAndCreate(
            PackLocationInfo(
                path.toString(),
                Component.literal("Pasture Block Fix"),
                PackSource.BUILT_IN,
                Optional.empty()
            ),
            factory,
            PackType.CLIENT_RESOURCES,
            PackSelectionConfig(true, Pack.Position.TOP, true)
        )
        event.addRepositorySource { consumer -> consumer.accept(profile) }
    }

    private fun registerCommands(e: RegisterCommandsEvent) {
        CobbreedingCommands.register(e.dispatcher, e.buildContext, e.commandSelection)
    }

}
